<template>
  <div v-loading.lock="loading" class="base-content system-menu-content">
    <div class="menu-tree">
      <div class="menu-tree-header">
        <span>{{ dataList.System }}</span>
        <el-select v-model="appKey" @change="changeApp">
          <el-option
            v-for="item in appList"
            :key="item.appKey"
            :value="item.appKey"
            :label="item.name"
          />
        </el-select>
      </div>

      <div class="menu-tree-header">
        <el-input
          v-model="queryMenuName"
          :placeholder="dataList.Search"
          clearable
          @clear="menuSearchClear"
          @keyup.enter.native="menuSearch"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="menuSearch"
          ></el-button>
        </el-input>
      </div>

      <el-tree
        class="customer-tree"
        :data="list"
        :props="defaultProps"
        default-expand-all
        @node-click="handleNodeClick"
      ></el-tree>
    </div>

    <div class="menu-detail">
      <div class="menu-content">
        <el-button type="primary" @click="menuAdd">{{ btn.Add }}</el-button>
        <template v-if="currentMenu.id">
          <el-button type="danger" @click="menuDelete">{{
            btn.Delete
          }}</el-button>
        </template>

        <el-form
          ref="menuData"
          class="menu-form"
          :model="menuData"
          :rules="menuDataRules"
          label-width="100px"
        >
          <el-form-item :label="dataList.Apply">
            <el-select v-model="menuData.appKey">
              <el-option
                v-for="item in appList"
                :key="item.appKey"
                :value="item.appKey"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="dataList.ParentMenu"
            prop="parentId"
            :error="menuErrorMsg.parentId"
          >
            <BaseTreeSelect
              v-model="currentMenu.parentId"
              :tree-data="menuTreeData"
              :placeholder="dataList.ParentMenu"
            />
          </el-form-item>
          <el-form-item
            :label="dataList.MenuName"
            prop="name"
            :error="menuErrorMsg.name"
          >
            <el-input v-model="menuData.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            :label="dataList.MenuEName"
            prop="eName"
            :error="menuErrorMsg.eName"
          >
            <el-input v-model="menuData.eName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.Icon" prop="icon">
            <el-input v-model="menuData.icon" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            :label="dataList.FrontEndRoute"
            prop="frontUrl"
            :error="menuErrorMsg.frontUrl"
          >
            <el-input v-model="menuData.frontUrl" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            :label="dataList.Component"
            prop="component"
            :error="menuErrorMsg.component"
          >
            <el-input
              v-model="menuData.component"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="dataList.BackEndRoute"
            prop="backendUrl"
            :error="menuErrorMsg.backendUrl"
          >
            <el-input
              v-model="menuData.backendUrl"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="dataList.Sort"
            prop="sort"
            :error="menuErrorMsg.sort"
          >
            <el-input
              v-model="menuData.sort"
              type="number"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item :label="dataList.ShowOrNot" prop="isShow">
            <el-switch
              v-model="menuData.isShow"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item :label="dataList.EnableOrNot" prop="status">
            <el-switch
              v-model="menuData.status"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button type="primary" @click="menuOnSubmit('menuData')">{{
            btn.Save
          }}</el-button>
        </div>
      </div>

      <div v-if="currentMenu.id" class="menu-operation">
        <el-button class="add-job-button" type="primary" @click="buttonAdd">{{
          dataList.Addbutton
        }}</el-button>
        <el-table :data="buttonList">
          <el-table-column prop="cName" :label="dataList.ButtonChineseName" />
          <el-table-column prop="eName" :label="dataList.ButtonEnglishName" />
          <el-table-column prop="backendUrl" :label="dataList.BackEndRoute" />
          <el-table-column :label="dataList.EnableOrNot">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                disabled
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="operation" :label="btn.operate" width="140">
            <template slot-scope="{ row }">
              <el-link type="primary" @click="buttonEdit(row)">{{
                btn.Edit
              }}</el-link>
              <el-divider
                class="base-content-table-divider"
                direction="vertical"
              />
              <el-link type="danger" @click="buttonDelete(row)">{{
                btn.Delete
              }}</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <PermissionButtonEdit
      ref="PermissionButtonEdit"
      :dialog-form-visible.sync="dialogFormVisible"
    />
  </div>
</template>

<script>
import {
  create,
  update,
  deleteRecord as menuDeleteRecord,
  getAllList,
} from "../../../api/Permission/PermissionMenu.js";
import { getAppAllList } from "../../../api/Permission/PermissionApp.js";
import {
  deleteRecord as buttonDeleteRecord,
  getAllList as buttonGetAllList,
} from "../../../api/Permission/PermissionButton.js";
import PermissionButtonEdit from "../PermissionButton/PermissionButtonEdit.vue";
import { formatData } from "../../../utils/index";
export default {
  name: "PermissionMenuList",
  components: { PermissionButtonEdit },
  data() {
    return {
      loading: true,
      list: [],
      queryMenuName: "", // 查询的菜单名称
      currentMenu: {}, // 当前选择的菜单
      defaultProps: {
        children: "children",
        label: "label",
      },
      dialogInfo: {},
      initMenuData: {
        id: 0,
        appKey: window.EnvConfig.VUE_APP_KEY,
        parentId: 0,
        name: "",
        eName: "",
        icon: "",
        frontUrl: "",
        backendUrl: "",
        component: "",
        sort: 1,
        isShow: "1",
        status: "1",
      },
      menuData: {
        id: 0,
        appKey: window.EnvConfig.VUE_APP_KEY,
        parentId: 0,
        name: "",
        eName: "",
        icon: "",
        frontUrl: "",
        backendUrl: "",
        component: "",
        sort: 1,
        isShow: "1",
        status: "1",
      },
      menuTreeData: [],
      menuDataRules: {
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
          {
            min: 1,
            max: 8,
            message: this.$t("Permission.PermissionUser.TheLength"),
            trigger: "blur",
          },
        ],
        frontUrl: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        backendUrl: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        component: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        sort: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionNumber,
          },
        ],
      },
      initMenuErrorMsg: {
        name: "",
        frontUrl: "",
        backendUrl: "",
        component: "",
        sort: "",
        eName: "",
      },
      menuErrorMsg: {
        name: "",
        frontUrl: "",
        backendUrl: "",
        component: "",
        sort: "",
        eName: "",
      },

      dialogFormVisible: false,
      buttonList: [],
      appKey: "",
      appList: [],
    };
  },
  computed: {
    btn() {
      return this.$t("Permission.buttons");
    },
    dataList() {
      return this.$t("Permission.PermissionUser");
    },
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      await getAppAllList().then((res) => {
        this.appList = res.data;
      });
      if (this.appList && this.appList.length) {
        this.appKey = window.EnvConfig.VUE_APP_KEY;
        this.changeApp();
      }
    },
    handleNodeClick(item) {
      this.currentMenu = item;
      this.menuData = this.currentMenu;
      console.log(this.menuData);
      this.getButtonList();
    },
    handleNodeClick2(item) {
      console.log(item);
    },
    // 选择系统
    changeApp() {
      this.getList();
    },
    menuSearch() {
      this.getList();
    },
    menuSearchClear() {
      this.getList();
    },
    menuAdd() {
      this.menuData = this.Helper.deepCopy(this.initMenuData);
      this.menuData.appKey = this.appKey;
      this.menuData.parentId = this.currentMenu.id;
    },
    menuDelete() {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        menuDeleteRecord({ id: this.currentMenu.id })
          .then((res) => {
            this.getList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    getList() {
      this.loading = true;
      getAllList({ name: this.queryMenuName, appKey: this.appKey })
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          const formatMenuData = formatData([
            {
              id: "0",
              name: this.$t("Permission.PermissionUser.FirstLevelMenu"),
              children: res.data.dataList,
            },
          ]);
          this.menuTreeData = formatMenuData;
          console.log(this.menuTreeData);
          this.recursionListSetStatusAndIsShow(this.list);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    recursionListSetStatusAndIsShow(tmpArray) {
      if (tmpArray && tmpArray.length > 0) {
        tmpArray.forEach((element) => {
          element.status = element.status + ""; // 将status值转换为字符串,方便switch组件调用
          element.isShow = element.isShow + "";
          this.recursionListSetStatusAndIsShow(element.children);
        });
      }
    },
    menuOnSubmit() {
      this.$refs.menuData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.menuErrorMsg = this.Helper.deepCopy(this.initMenuErrorMsg);
          if (this.menuData.id <= 0) {
            create(this.menuData)
              .then((res) => {
                if (res.code === 200) {
                  this.getList();
                  this.closeDialog();
                } else {
                  this.showValidateMenuMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update(this.menuData)
              .then((res) => {
                if (res.code === 200) {
                  this.getList();
                  this.closeDialog();
                } else {
                  this.showValidateMenuMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMenuMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("name", this.menuErrorMsg, res.msg);
        this.Helper.showValidateMsg("frontUrl", this.menuErrorMsg, res.msg);
        this.Helper.showValidateMsg("backendUrl", this.menuErrorMsg, res.msg);
        this.Helper.showValidateMsg("component", this.menuErrorMsg, res.msg);
        this.Helper.showValidateMsg("sort", this.menuErrorMsg, res.msg);
        this.Helper.showValidateMsg("eName", this.menuErrorMsg, res.msg);
      }
    },

    getButtonList() {
      if (this.currentMenu.id > 0) {
        this.loading = true;
        buttonGetAllList({ menuId: this.currentMenu.id })
          .then((res) => {
            if (res.data) {
              this.buttonList = res.data.dataList ? res.data.dataList : [];
              this.buttonList.forEach((s) => {
                s.status = s.status + "";
              });
            }
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    buttonAdd() {
      this.$refs.PermissionButtonEdit.formData = this.Helper.deepCopy(
        this.$refs.PermissionButtonEdit.initData
      );
      this.$refs.PermissionButtonEdit.formData.menuId = this.currentMenu.id;
      this.dialogFormVisible = true;
    },
    buttonEdit(rowData) {
      this.$refs.PermissionButtonEdit.formData = rowData;
      this.dialogFormVisible = true;
    },
    buttonDelete(rowData) {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        buttonDeleteRecord({ id: rowData.id })
          .then((res) => {
            this.getButtonList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
  },
};
</script>

<style lang="scss">
.system-menu-content {
  padding: 0;
  background: #f8fbff;
  display: flex;
  align-items: flex-start;
  .menu-tree {
    width: 290px;
    height: 100%;
    // overflow: auto;
    .menu-tree-header {
      width: 100%;
      padding: 16px 12px 12px;
      box-sizing: border-box;
      color: #4e4e4e;
      display: flex;
      align-items: center;
      & > span {
        font-size: 14px;
        font-weight: 600;
        display: block;
        margin-right: 12px;
      }
    }
    .el-tree {
      height: calc(100% - 64px) !important;
      overflow: auto !important;
    }
  }
  .menu-detail {
    width: calc(100% - 260px);
    height: 100%;
    background: #fff;
    padding: 20px 0 20px 20px;
    overflow-y: auto;
    box-sizing: border-box;
    position: relative;
    display: flex;
    align-items: flex-start;
    .menu-content {
      width: 50%;
      border-right: 1px #dedede solid;
    }
    .empty {
      height: calc(100% - 40px);
    }
    .menu-operation {
      width: 50%;
      padding: 0 24px;
      box-sizing: border-box;
    }
  }
  .customer-tree {
    background: #f8fbff;
    .el-tree-node__content {
      height: 40px !important;
      line-height: 40px !important;
      &:hover {
        color: #4787ff !important;
        background: rgba(47, 113, 245, 0.2) !important;
      }
      .el-tree-node__label {
        font-size: 12px !important;
      }
      .el-tree-node__expand-icon {
        font-size: 16px !important;
        font-weight: bold !important;
        color: #999;
      }
      .is-leaf {
        color: transparent;
      }
    }
    .is-current {
      & > .el-tree-node__content {
        .el-tree-node__label {
          color: #4787ff !important;
          font-weight: 600 !important;
        }
        .el-tree-node__expand-icon {
          color: #4787ff !important;
        }
        .is-leaf {
          color: transparent;
        }
      }
    }
  }
  .menu-form {
    margin-top: 32px;
    .el-form-item--small {
      margin-right: 24px !important;
    }
    .el-select {
      width: 100% !important;
    }
  }
}
</style>
